package com.jiangyg.mall.authz.service.impl;

import com.google.code.kaptcha.Producer;
import com.jiangyg.mall.authz.service.CaptchaService;
import com.jiangyg.mall.core.support.env.EnvConstant;
import com.jiangyg.mall.core.exception.BusinessException;
import com.jiangyg.mall.core.support.cache.CacheAdapter;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.function.Function;

/**
 * 类描述：
 *
 * @author jiangyg
 * @date 2021-10-18
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

    private final Producer producer;

    private final CacheAdapter cacheAdapter;

    /**
     * 验证码Key生成函数
     */
    private final Function<String, String> captchaKeyCreate = (uuid) -> String.format("mauz:captcha:%s", uuid);

    @Autowired
    public CaptchaServiceImpl(@Qualifier("kaptchaProducer") Producer producer,
                              @Qualifier("cacheAdapter") CacheAdapter cacheAdapter) {
        this.producer = producer;
        this.cacheAdapter = cacheAdapter;
    }

    @Override
    public BufferedImage createCaptcha(String uuid) {
        // 1. 校验 uuid 参数不能为空
        if (StringUtils.isBlank(uuid)) {
            throw new BusinessException("生成验证码失败：uuid不能为空！");
        }
        // 2. 生成文字验证码
        final String code = producer.createText();
        // 3. 放入缓存，过期时间1分钟
        final String captchaKey = captchaKeyCreate.apply(uuid);
        cacheAdapter.put(captchaKey, code, 60);
        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        // 1. 验证码和uuid参数都不能为空
        if (StringUtils.isBlank(uuid) || StringUtils.isBlank(code)) {
            return false;
        }
        // 2. 测试专用
        if (StringUtils.equals(uuid, "test")
                && StringUtils.equals(EnvConstant.profile(), "dev")) {
            return true;
        }
        // 3. 获取并移除缓存中的验证码
        final String captchaKey = captchaKeyCreate.apply(uuid);
        final String value = cacheAdapter.get(captchaKey);
        cacheAdapter.remove(captchaKey);
        // 4. 比较用户输入验证码是否正确，不区分大小写
        return StringUtils.equalsIgnoreCase(code, value);
    }

}
